/**
 * 完成一个’flatten’的函数，实现“拍平”一个多维数组为一维。示例如下：
 * var testArr1 = [[0, 1], [2, 3], [4, 5]];
 * var testArr2 = [0, [1, [2, [3, [4, [5]]]]]];
 * flatten(testArr1) // [0, 1, 2, 3, 4, 5]
 * flatten(testArr2) // [0, 1, 2, 3, 4, 5]
 */
var testArr1 = [[0, 1], [2, 3], [4, 5]];
var testArr2 = [0, [1, [2, [3, [4, [5]]]]]];
var testArr3 = [0, [1, [2, [3, [4, 5]]]]];

//最简单的解法
var flatten = (arr) => arr.toString().split(',').map((val) => parseInt(val));

// aa = flatten(testArr1);
// console.log(testArr2.toString());
// console.log(aa);

var flatten2 = function (arr) {
  return arr.reduce(function (pre, val) {
    if(Array.isArray(val)){
      pre.push(...flatten2(val));
    }else{
      pre.push(val);
    }
    return pre;
  }, []);
};
console.log(flatten2(testArr1));
console.log(flatten2(testArr2));
console.log(flatten2(testArr3));

Array.prototype.flat = function(){
  return this.reduce(function(pre, cur){
    if(Array.isArray(cur)){
      pre.push(...cur.flat());
    }else{
      pre.push(cur);
    }
    return pre;
  }, []);
};

const arr = [1, [2], [3, [4]]];
var data = arr.flat();
console.log(data);

